import VuiElement from '../../base/element';
import VuiContainer from '../../components/container';
import VuiDropdown from '../../components/dropdown';
import VuiText from '../../components/text';
import './style.css';
import VuiSelectTagList from './tag-list';

export default class VuiMutliTagSelect extends VuiElement {
  constructor(config) {
    super();
    const defaultConfig = {
      id: null,
      enabled: true,
      showcaseWidth: 80,
      dropdownWidth: 120,
      options: [],
      title: null,
      showTitle: false,
      action: _ => {}
    };

    this._config = Object.assign(defaultConfig, config);
    this._className = {
      container: 'vui-mtselect',
      content: 'vui-mtselect-content',
      title: 'vui-mtselect-title',
      placeholder: 'vui-mtselect-placeholder'
    };
  }

  init() {
    const cls = this._className;
    const config = this._config;
    // 容器
    this.initContainer(null, null, config.id);

    // 标题
    if (config.showTitle) {
      const title = VuiText.newInstance(config.title, cls.title);
      this.append(title);
    }

    // 显示区
    const content = VuiContainer.newInstance(cls.content);
    this.tagList = new VuiSelectTagList().init();
    this.tagList.setWidth(config.showcaseWidth);
    this.placeholder = VuiContainer.newInstance(cls.placeholder);
    this.placeholder.setVisible(false);

    content.append([this.tagList, this.placeholder]);

    // 下拉列表
    const dp = VuiDropdown.newInstance();
    dp.setWidth(config.dropdownWidth);
    dp.setTopLeft(16, 0);

    dp.setOptions(config.options, (value, text) => {
      this.safeRun(config.action, value, text);
      this.tagList.addTag({ value, text });
    });
    const dpToggle = evt => {
      if (config.enabled) {
        dp.toggle();
      }
      evt.stopPropagation();
    };

    content.addEventListener('click', dpToggle);

    this.dropdown = dp;
    content.append(dp);
    this.append(content);
    return this;
  }

  setClickListener(listener) {
    if (typeof listener === 'function') {
      this._config.action = listener;
    }
  }

  getSelectTags() {
    return this.tagList.tags;
  }
}
